<?php

namespace App\Jobs;

use App\Lib\WeApp\WeApp;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxLike;
use App\Models\User\WxUser;
use App\Models\User\WxUserWithdrawal;
use App\Models\WxAuthentication;
use App\Models\WxOrder;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;

class SubscribeMessageJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $type = '';
    protected $object_id = 0;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($type, $object_id)
    {
        $this->type = $type;
        $this->object_id = $object_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        global $__MINI_GLOBAL_PAYCODE_2__;
        if(!$__MINI_GLOBAL_PAYCODE_2__){
            return null;
        }

        if(_empty_($this->type) || _empty_($this->object_id)){
            return null;
        }

        $weapp = new WeApp();
        $templateMsg = $weapp->getTemplateMsg();

        if($this->type == 'comment_add'){
            $comment = WxComment::find($this->object_id);
            if(_empty_($comment)){
                return;
            }
            $posts_id = $comment->posts_id;
            $posts_user_id = $comment->posts_user_id;
            $user_id = $comment->user_id;
            $comment_content = $comment->comment_content;
            $open_id = WxUser::where('id', $posts_user_id)->value('weixin_openid');
            $templete_id = Settings::get('mini_template_message_comment_add', '');

            if(Cache::has($posts_user_id.':'.'subscribe:'.$posts_id.':'.$templete_id)){
                return;
            }

            $data = [
                'thing5' => [
                    'value' => $comment->is_anonymous == 1 ? StrUtils::limit(UserUtils::get_cached_user($comment->user_id)['anonymous_name']) : StrUtils::limit(UserUtils::get_cached_user($comment->user_id)['user_name'])
                ],
                'time3' => [
                    'value' => $comment->created_at->toDateTimeString()
                ],
                'thing2' => [
                    'value' => StrUtils::limit(strip_tags( _mini_phone(_mini_emoji(_mini_aite_replace($comment_content, true), true), true)))
                ]
            ];
            $mini_path = '/pages/sticky/sticky?id='.$posts_id;

            try{
                $res = $templateMsg->subscribeMessage( $open_id ,$templete_id,$data, $mini_path );
            }catch (\Exception $e){
                _logger_(__file__, __line__, $e->getMessage());
                if(strpos($e->getMessage(), '43101:') === 0){
                    Cache::put($posts_user_id.':'.'subscribe:'.$posts_id.':'.$templete_id, 'no', 3600 * 12 );
                }
                return;
            }


        }else if($this->type == 'comment_reply'){
            $comment = WxComment::find($this->object_id);
            if(_empty_($comment)){
                return;
            }

            $comment_comment_id = $comment->comment_id;
            if(_empty_($comment_comment_id)){
                return;
            }

            $comment_comment = WxComment::find($comment_comment_id);
            $posts_id = $comment->posts_id;

            $comment_comment_user_id = $comment_comment->user_id;
            // 原评论
            $comment_content = $comment->comment_content;

            $open_id = WxUser::where('id', $comment_comment_user_id)->value('weixin_openid');
            $templete_id = Settings::get('mini_template_message_comment_reply', '');

            if(Cache::has($comment_comment_user_id.':'.'subscribe:'.$comment_comment_id.':'.$templete_id)){
                return;
            }

            $data = [
                'thing1' => [
                    'value' => StrUtils::limit(strip_tags( _mini_phone(_mini_emoji(_mini_aite_replace($comment_comment->comment_content, true), true), true))),
                ],
                'thing2' => [
                    'value' => StrUtils::limit(strip_tags( _mini_phone(_mini_emoji(_mini_aite_replace($comment_content, true), true), true))),
                ],
                'thing3' => [
                    'value' => $comment->is_anonymous == 1 ? StrUtils::limit(UserUtils::get_cached_user($comment->user_id)['anonymous_name']) : StrUtils::limit(UserUtils::get_cached_user($comment->user_id)['user_name'])
                ],
                'time4' => [
                    'value' => $comment_comment->created_at->toDateTimeString()
                ],
                'thing10' => [
                    'value' => StrUtils::limit(PostUtils::get_the_title('', $posts_id))
                ],
            ];
            $mini_path = '/pages/sticky/sticky?id='.$posts_id;

            try{
                $res = $templateMsg->subscribeMessage( $open_id ,$templete_id,$data, $mini_path );
            }catch (\Exception $e){
                _logger_(__file__, __line__, $e->getMessage());
                if(strpos($e->getMessage(), '43101:') === 0){
                    Cache::put($comment_comment_user_id.':'.'subscribe:'.$comment_comment_id.':'.$templete_id, 'no', 3600 * 12 );
                }
                return;
            }


        }else if($this->type == 'exceptional'){

            $order = WxOrder::find($this->object_id);
            if(_empty_($order) || $order->order_type != 2){
                return;
            }

            $parame = unserialize($order->parame);
            $posts_id = $parame['postsId'];
            $posts_user_id = $parame['postsUserId'];
            $user_id = $order->user_id;

            $order_pay_price= $order->order_pay_price;
            $open_id = WxUser::where('id', $posts_user_id)->value('weixin_openid');
            $templete_id = Settings::get('mini_template_message_exceptional', '');
            $tip = '「'.UserUtils::get_cached_user($user_id)['user_name'] .'」给您的笔记充电了￥'.$order_pay_price;

            if(Cache::has($posts_user_id.':'.'subscribe:'.$posts_id.':'.$templete_id)){
                return;
            }

            $data = [
                'date1' => [
                    'value' => $order->created_at->toDateTimeString()
                ],
                'thing2' => [
                    'value' => StrUtils::limit($tip)
                ],
            ];
            $mini_path = '/pages/sticky/sticky?id='.$posts_id;

            try{
                $res = $templateMsg->subscribeMessage( $open_id ,$templete_id, $data, $mini_path );
            }catch (\Exception $e){
                _logger_(__file__, __line__, $e->getMessage());
                if(strpos($e->getMessage(), '43101:') === 0){
                    Cache::put($posts_user_id.':'.'subscribe:'.$posts_id.':'.$templete_id, 'no', 3600 * 12 );
                }
                return;
            }

        }else if($this->type == 'gicecoin'){
            $comment = WxComment::find($this->object_id);
            if(_empty_($comment)){
                return;
            }
            $posts_id = $comment->posts_id;
            $posts_user_id = $comment->posts_user_id;
            $user_id = $comment->user_id;
            $comment_content = $comment->comment_content;
            $open_id = WxUser::where('id', $posts_user_id)->value('weixin_openid');
            $templete_id = Settings::get('mini_template_message_exceptional', '');

            if(Cache::has($posts_user_id.':'.'subscribe:'.$posts_id.':'.$templete_id)){
                return;
            }

            $data = [
                'date1' => [
                    'value' => $comment->created_at->toDateTimeString()
                ],
                'thing2' => [
                    'value' => StrUtils::limit(strip_tags( _mini_phone( _mini_emoji(_mini_aite_replace($comment_content, true), true), true )))
                ],
            ];
            $mini_path = '/pages/sticky/sticky?id='.$posts_id;

            try{
                $res = $templateMsg->subscribeMessage( $open_id ,$templete_id,$data, $mini_path );
            }catch (\Exception $e){
                _logger_(__file__, __line__, $e->getMessage());
                if(strpos($e->getMessage(), '43101:') === 0){
                    Cache::put($posts_user_id.':'.'subscribe:'.$posts_id.':'.$templete_id, 'no', 3600 * 12 );
                }
                return;
            }
        }else if($this->type == 'beliked'){
            $like_obj = WxLike::find($this->object_id);
            if(_empty_($like_obj)){
                return;
            }
            $posts_id = $like_obj->posts_id;
            $posts_user_id = $like_obj->posts_user_id;
            $user_id = $like_obj->user_id;
            $open_id = WxUser::where('id', $posts_user_id)->value('weixin_openid');
            $templete_id = Settings::get('mini_template_message_beliked', '');

            if(Cache::has($posts_user_id.':'.'subscribe:'.$posts_id.':'.$templete_id)){
                return;
            }

            $data = [
                'name1' => [
                    'value' => StrUtils::limit(UserUtils::get_cached_user($user_id)['user_name'], 10)
                ],
                'date2' => [
                    'value' => $like_obj->created_at->toDateTimeString()
                ],
                'thing3' => [
                    'value' => StrUtils::limit(PostUtils::get_the_title('', $posts_id))
                ]
            ];
            $mini_path = '/pages/sticky/sticky?id='.$posts_id;

            try{
                $res = $templateMsg->subscribeMessage( $open_id ,$templete_id,$data, $mini_path );
            }catch (\Exception $e){
                _logger_(__file__, __line__, $e->getMessage());
                if(strpos($e->getMessage(), '43101:') === 0){
                    Cache::put($posts_user_id.':'.'subscribe:'.$posts_id.':'.$templete_id, 'no', 3600 * 12 );
                }
                return;
            }
        }else if($this->type == 'withdrawal'){
            $withdrawal_obj = WxUserWithdrawal::find($this->object_id);
            if(_empty_($withdrawal_obj)){
                return;
            }
            $user_id = $withdrawal_obj->user_id;
            $open_id = WxUser::where('id', $user_id)->value('weixin_openid');
            $templete_id = Settings::get('mini_template_message_withdrawal', '');
            $mini_path = '/pages/tabbar/index/index';

            if(Cache::has($user_id.':'.'subscribe:'.$this->object_id.':'.$templete_id)){
                return;
            }

            $state_tip = '';
            $msg = '';
            if($withdrawal_obj->state == 0){
                $state_tip = '未审核';
                $msg = '管理员暂时还没未审核，请耐心等待';
            }else if($withdrawal_obj->state == 1){
                $state_tip = '已打款';
                if($withdrawal_obj->wechat_phone){
                    $msg = '提现途径为：微信手机号' . $withdrawal_obj->wechat_phone . '，请注意查收';
                }else if($withdrawal_obj->alipay_phone){
                    $msg = '提现途径为：支付宝手机号' . $withdrawal_obj->alipay_phone . '，请注意查收';
                }else if($withdrawal_obj->bank_card){
                    $msg = '您的提现银行为' . $withdrawal_obj->bank_name . '，请注意查收';
                }
            }else if($withdrawal_obj->state == 2){
                $state_tip = '被拒绝';
                $msg = $withdrawal_obj->refuse_tip;
            }


            $data = [
                'amount2' => [
                    'value' => $withdrawal_obj->price
                ],
                'time3' => [
                    'value' => $withdrawal_obj->created_at->toDateTimeString()
                ],
                'phrase4' => [
                    'value' =>StrUtils::limit($state_tip)
                ],
                'thing5' => [
                    'value' =>StrUtils::limit($msg)
                ],
            ];

            try{
                $res = $templateMsg->subscribeMessage( $open_id ,$templete_id, $data, $mini_path );
            }catch (\Exception $e){
                _logger_(__file__, __line__, $e->getMessage());
                if(strpos($e->getMessage(), '43101:') === 0){
                    Cache::put($user_id.':'.'subscribe:'.$this->object_id.':'.$templete_id, 'no', 3600 * 12 );
                }
                return;
            }
        }else if($this->type == 'authentication'){

            $authentication_obj = WxAuthentication::find($this->object_id);
            if(_empty_($authentication_obj)){
                return;
            }
            $user_id = $authentication_obj->user_id;
            $open_id = WxUser::where('id', $user_id)->value('weixin_openid');
            $templete_id = Settings::get('mini_template_message_authentication', '');
            $mini_path = '/pages/tabbar/index/index';

            if(Cache::has($user_id.':'.'subscribe:'.$this->object_id.':'.$templete_id)){
                return;
            }

            $auth_state = '';
            if($authentication_obj->authentication_state == 0){
                $auth_state = '审核中';
            }else if($authentication_obj->authentication_state == 1){
                $auth_state = '审核通过';
            }else if($authentication_obj->authentication_state == 1){
                $auth_state = '驳回';
            }

            $data = [
                'phrase1' => [
                    'value' => $auth_state
                ],
                'thing2' => [
                    'value' => StrUtils::limit($authentication_obj->name)
                ],
                'date3' => [
                    'value' => $authentication_obj->created_at->toDateTimeString()
                ],
            ];

            try{
                $res = $templateMsg->subscribeMessage( $open_id ,$templete_id, $data, $mini_path );
            }catch (\Exception $e){
                _logger_(__file__, __line__, $e->getMessage());
                if(strpos($e->getMessage(), '43101:') === 0){
                    Cache::put($user_id.':'.'subscribe:'.$this->object_id.':'.$templete_id, 'no', 3600 * 12 );
                }
                return;
            }
        }

    }
}
